import os

def save_equation(support, weights, bias, sign, l1_loss, l2_loss, path):
    """
    :param support: list -> [True, False, ... True]  若list[i]==True， 表示需要 x_i
    :param weight: list -> 表示x_i对应的权重
    :param bias:  torch.float32    偏置
    :param sign: str -> 给每个方程一个名字
    :param l1_loss: float, l1损失
    :param l2_loss: float, l2损失
    :param path: 保存文件
    :return:
    """

    if not os.path.exists(path):
        file = open(path, 'a', encoding="utf-8")
        file.write("name,equation,L1,L2")
        file.flush()
        file.close()
    file = open(path, 'a', encoding="utf-8")
    num = 1
    equation = 'Y = '
    index = 0
    for x_i, i in enumerate(support,1):
        if i:
            weight = weights[index]
            index += 1

            equation = equation + '(%.4f)X%d' % (weight, x_i) + ' + '
    equation = equation + '%.2f'%bias
    file.write('\n%s,%s,%.2f,%.2f'%(sign, equation, l1_loss, l2_loss))
    file.close()


class Avg:
    def __init__(self):
        self.sum = 0
        self.n = 0
        self.mean = 0

    def __call__(self, num):
        self.sum += num
        self.n += 1
        self.mean = self.sum / self.n
        return self.mean
